<?php

namespace App\Http\Controllers\Admin;

use App\Model\Cate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CateController extends Controller
{
    public function index()
    {
//        $permission = Cate::sortCate();
        $permission = (new Cate)->sortCate();
        return view('admin.cate.list',compact('permission'));
    }

    public function create()
    {
        $cate = Cate::where('pid',0)->get();
        return view('admin.cate.add',compact('cate'));
    }

    public function store(Request $request)
    {
        $input = $request->all();
        $res = Cate::create($input);
        if($res){
            echo json_encode([
                "code"=>1,
                "msg"=>"success"
            ]);
        }else{
            echo json_encode([
                "code"=>0,
                "msg"=>"error"
            ]);
        }
    }

    public function edit($id)
    {
        $cate = Cate::find($id);
        $pcate = Cate::where('pid',0)->get();
        return view('admin.cate.edit',compact('cate','pcate'));
    }

    public function update(Request $request, $id)
    {
        $user = $request -> all();
        $res = Cate::where("id",$id)->update($user);
        if($res){
            echo json_encode([
                "code"=>1,
                "msg"=>"success"
            ]);
        }else{
            echo json_encode([
                "code"=>0,
                "msg"=>"error"
            ]);
        }
    }

    public function destroy($id)
    {
        $user = Cate::find($id);
        $res = $user->delete();
        if($res){
            $data = array(
                "status"=>0,
                "message"=>"删除成功"
            );
        }else{
            $data = array(
                "status"=>1,
                "message"=>"删除失败"
            );
        }
        return $data;
    }

    public function delAll(Request $request){
        $res = Cate::destroy($request->input('ids'));
        if($res){
            $data = array(
                "status"=>0,
                "message"=>"删除成功"
            );
        }else{
            $data = array(
                "status"=>1,
                "message"=>"删除失败"
            );
        }
        return $data;
    }

    public function changeOrder(Request $request){
        $input = $request -> except("_token");
        $cate = Cate::find($input['id']);

        $res = $cate -> update(["order"=>$input['order']]);

        if($res){
            $data = [
                "status"    =>  0,
                "msg"       =>  "修改成功"
            ];
        }else{
            $data = [
                "status"    =>  1,
                "msg"       =>  "修改失败"
            ];
        }

        return $data;
    }
}
